<template>
  <div class="text-message">
    <!-- 消息头部信息 - 所有消息都显示 -->
    <div class="message-header">
      <el-avatar
        :size="32"
        :src="message.senderAvatar"
        :alt="message.senderName"
      >
        {{ message.senderName?.charAt(0) }}
      </el-avatar>
      <div class="sender-info">
        <span class="sender-name" :class="{ 'own-sender': isOwn }">
          {{ message.senderName }}
          <span v-if="isOwn" class="own-tag">（我）</span>
        </span>
        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
      </div>

      <!-- 消息状态（仅自己的消息显示） -->
      <div v-if="isOwn" class="message-status">
        <el-icon v-if="message.messageStatus === 'sending'" class="status-sending">
          <Loading />
        </el-icon>
        <el-icon v-else-if="message.messageStatus === 'sent'" class="status-sent">
          <Check />
        </el-icon>
        <el-icon v-else-if="message.messageStatus === 'failed'" class="status-failed">
          <Close />
        </el-icon>
      </div>

      <!-- 加密状态指示器 -->
      <div v-if="message.isEncrypted" class="encryption-status">
        <el-tooltip content="此消息已加密" placement="top">
          <el-icon class="encryption-icon">
            <Lock />
          </el-icon>
        </el-tooltip>
      </div>
    </div>

    <!-- 消息内容 -->
    <div class="message-content">
      <div class="message-bubble" :class="{ 'own-bubble': isOwn }">
        <!-- 消息文本 -->
        <div class="message-text">{{ message.content }}</div>
      </div>
    </div>

    <!-- 消息操作菜单 -->
    <div class="message-actions" v-show="showActions">
      <el-button-group size="small">
        <el-button :icon="ChatLineRound" @click="replyMessage" title="回复">
        </el-button>
        <el-button :icon="CopyDocument" @click="copyMessage" title="复制">
        </el-button>
        <el-button 
          v-if="isOwn" 
          :icon="Delete" 
          @click="deleteMessage" 
          title="删除"
          type="danger"
        >
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Loading,
  Check,
  Close,
  ChatLineRound,
  CopyDocument,
  Delete,
  Lock
} from '@element-plus/icons-vue'

// 类型定义
interface TeamMessage {
  id: number | string
  teamId: number
  senderId: number
  senderName: string
  senderAvatar?: string
  messageType: 'text' | 'image' | 'file'
  content: string
  messageStatus: 'sending' | 'queued' | 'sent' | 'delivered' | 'failed'
  timestamp: number
  // 加密相关字段
  iv?: string
  encryptionAlgorithm?: string
  keyVersion?: number
  isEncrypted?: boolean
}

// Props
interface Props {
  message: TeamMessage
  isOwn: boolean
}

const props = defineProps<Props>()

// 响应式数据
const showActions = ref(false)

// 计算属性
const formattedContent = computed(() => {
  let content = props.message.content
  
  // 处理换行
  content = content.replace(/\n/g, '<br>')
  
  // 处理链接（简单的URL检测）
  const urlRegex = /(https?:\/\/[^\s]+)/g
  content = content.replace(urlRegex, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>')
  
  // 处理@提及（如果需要）
  // const mentionRegex = /@(\w+)/g
  // content = content.replace(mentionRegex, '<span class="mention">@$1</span>')
  
  return content
})

// 方法
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1分钟显示"刚刚"
  if (diff < 60000) {
    return '刚刚'
  }
  
  // 小于1小时显示分钟
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  
  // 小于24小时显示小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  
  // 今天显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })}`
  }
  
  // 其他显示日期时间
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const replyMessage = () => {
  // TODO: 实现回复功能
  ElMessage.info('回复功能开发中...')
}

const copyMessage = async () => {
  try {
    await navigator.clipboard.writeText(props.message.content)
    ElMessage.success('消息已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const deleteMessage = () => {
  // TODO: 实现删除功能
  ElMessage.info('删除功能开发中...')
}

// 鼠标悬停显示操作按钮
const handleMouseEnter = () => {
  showActions.value = true
}

const handleMouseLeave = () => {
  showActions.value = false
}
</script>

<style scoped lang="scss">
.text-message {
  position: relative;
  margin-bottom: 16px;

  &:hover .message-actions {
    opacity: 1;
  }
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;

  .sender-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 2px;

    .sender-name {
      font-size: 14px;
      font-weight: 600;
      color: var(--el-color-primary);

      &.own-sender {
        color: var(--el-color-success);
      }

      .own-tag {
        font-size: 12px;
        font-weight: normal;
        color: var(--el-text-color-secondary);
      }
    }

    .message-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }

  .message-status {
    display: flex;
    align-items: center;
    gap: 4px;

    .status-sending {
      color: var(--el-color-warning);
      animation: spin 1s linear infinite;
    }

    .status-sent {
      color: var(--el-color-success);
    }

    .status-failed {
      color: var(--el-color-danger);
    }
  }

  .encryption-status {
    display: flex;
    align-items: center;
    margin-left: 8px;

    .encryption-icon {
      font-size: 12px;
      color: var(--el-color-success);
      opacity: 0.7;
      transition: opacity 0.2s;

      &:hover {
        opacity: 1;
      }
    }
  }
}

.message-content {
  position: relative;
  max-width: 80%;
  margin-left: 40px; // 对齐头像右侧
}

.message-bubble {
  position: relative;
  padding:6px 8px;
  border-radius: 7px;
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color-lighter);
  word-wrap: break-word;
  word-break: break-word;

  &.own-bubble {
    background: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-7);

    .message-text {
      color: var(--el-color-primary);
      font-weight: 500;
    }
  }

  // 简化的左侧箭头
  &::before {
    content: '';
    position: absolute;
    top: 12px;
    left: -8px;
    width: 0;
    height: 0;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-right: 8px solid var(--el-bg-color-page);
  }

  &.own-bubble::before {
    border-right-color: var(--el-color-primary-light-9);
  }
}

.message-text {
  line-height: 1.5;
  font-size: 14px;
  color: var(--el-text-color-primary);
  white-space: pre-wrap;
  word-break: break-word;

  // 链接样式
  :deep(a) {
    color: var(--el-color-primary);
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }

  .own-bubble & :deep(a) {
    color: rgba(255, 255, 255, 0.9);
  }

  // 提及样式
  :deep(.mention) {
    color: var(--el-color-primary);
    font-weight: 600;
    background: var(--el-color-primary-light-9);
    padding: 2px 4px;
    border-radius: 4px;
  }
}

// 动画
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.message-actions {
  position: absolute;
  top: -8px;
  right: 16px;
  opacity: 0;
  transition: opacity 0.2s;
  background: var(--el-bg-color);
  border-radius: 6px;
  box-shadow: var(--el-box-shadow-light);
  z-index: 10;

  .own-message & {
    right: auto;
    left: 16px;
  }

  .el-button-group {
    .el-button {
      border-radius: 4px;
      padding: 4px 8px;
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .message-content {
    max-width: 85%;
  }

  .message-bubble {
    padding: 10px 12px;
    font-size: 14px;
  }

  .message-actions {
    position: static;
    opacity: 1;
    margin-top: 8px;
    background: transparent;
    box-shadow: none;
  }
}
</style>
